package org.example.job;

import org.apache.shardingsphere.elasticjob.api.ShardingContext;
import org.apache.shardingsphere.elasticjob.dataflow.job.DataflowJob;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * lasticjob-lite-spring-boot-starter,配置方式
 */
@Component
public class SpringBootDateFlowJob implements DataflowJob<Long> {
    private long lastHandleTime = 0;

    /**
     * 查询数据
     *
     * @param shardingContext 分片上下文
     * @return
     */
    @Override
    public List<Long> fetchData(ShardingContext shardingContext) {
        System.out.println(String.format("查询数据:------Thread ID: %s, 任务总片数: %s, 当前分片项: %s",
                Thread.currentThread().getId(), shardingContext.getShardingTotalCount(), shardingContext.getShardingItem()));
        return queryData();
    }

    private List<Long> queryData() {
        ArrayList<Long> arrayList = new ArrayList<>();
        if (System.currentTimeMillis() - lastHandleTime < 20 * 1000) {
            return arrayList;
        }

        arrayList.add(1L);
        arrayList.add(2L);
        arrayList.add(3L);
        arrayList.add(4L);
        lastHandleTime = System.currentTimeMillis();
        return arrayList;
    }

    /**
     * 处理数据
     *
     * @param shardingContext 分片上下文
     * @param list            待处理数据集合
     */
    @Override
    public void processData(ShardingContext shardingContext, List<Long> list) {
        System.out.println(String.format("处理数据:------Thread ID: %s, 任务总片数: %s, 当前分片项: %s,list: %s ",
                Thread.currentThread().getId(), shardingContext.getShardingTotalCount(), shardingContext.getShardingItem(), list));
    }
}
